package uk.ac.lkl.common.associator.ui;



import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import uk.ac.lkl.common.ui.SwingUtilities2;
import uk.ac.lkl.common.util.ds.AbstractNotifyingList;


public class DeleteListener {

    private JPopupMenu menu;


    private NewAssociatorView associatorView;


    private HashMap<Component, Component> childMap = new HashMap<Component, Component>();


    private MouseListener mouseListener = new MouseAdapter() {

        public void mousePressed(MouseEvent e) {
            processMousePressed(e);
        }
    };


    public DeleteListener(NewAssociatorView associatorView) {
        this.associatorView = associatorView;
        createMenu();
    }


    private void createMenu() {
        this.menu = new JPopupMenu();
        JMenuItem deleteItem = new JMenuItem("Delete");
        deleteItem.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                delete();
            }
        });
        menu.add(deleteItem);
    }


    public void addViewPanel(AssociationViewPanel viewPanel) {
        viewPanel.addMouseListener(mouseListener);

        ArrayList<Component> components = SwingUtilities2
                .getMouseComponents(viewPanel);

        for (Component subComponent : components) {
            subComponent.addMouseListener(mouseListener);
            childMap.put(subComponent, viewPanel);
        }
    }


    public void processMousePressed(MouseEvent e) {
        if (e.getButton() != MouseEvent.BUTTON3)
            return;

        Object source = e.getSource();

        Component eventComponent = (Component) e.getSource();
        Component mappedComponent = childMap.get(eventComponent);

        Component deleteComponent = mappedComponent == null ? eventComponent
                : mappedComponent;

        if (!(deleteComponent instanceof AssociationViewPanel))
            return;

        AssociationViewPanel viewPanel = (AssociationViewPanel) deleteComponent;
        int height = viewPanel.getHeight();
        menu.show(viewPanel, 0, height);
    }


    private void delete() {
        Component invoker = menu.getInvoker();
        if (invoker == null)
            return;

        if (!(invoker instanceof AssociationViewPanel))
            return;

        AssociationViewPanel<?> viewPanel = (AssociationViewPanel<?>) invoker;
        Class<?> modelClass = viewPanel.getModelClass();
        AbstractNotifyingList<?> list = associatorView.getList(modelClass);
        Object model = viewPanel.getModel();
        list.remove(model);
    }

}
